
export function fetchPOST(url, data) {
    const headers = {
        "Content-Type": "application/json",
        'Access-Token': sessionStorage.getItem('access-token') || '' // 从sessionStorage中获取access token
    };
    const body = typeof data === 'string' ? data : JSON.stringify(data);
    return fetch(url, { method: 'POST', headers: headers, body: body })
        .then((res) => {
            if (res.status === 401) {
                location = "/#/login";
                return Promise.reject('Unauthorized.');
            } else {
                const token = res.headers.get('access-token');
                if (token) {
                    sessionStorage.setItem('access-token', token)
                }
                return res.json();
            }
        });

}

export function fetchGET(url, params) {
    const _url = encodeURL(url, params);
    const headers = {
        'Content-Type': 'application/json',
        'Access-Token': sessionStorage.getItem('access-token') || '' // 从sessionStorage中获取access token 
    };
    return fetch(_url, { method: 'GET', headers: headers }).then((res) => {
        if (res.status === 401) {
            location = "/#/login";
            return Promise.reject('Unauthorized.');
        } else {
            const token = res.headers.get('access-token');
            if (token) {
                sessionStorage.setItem('access-token', token)
            }
            return res.json();
        }
    });
}

export function reader(file, options = {}) {
    return new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.onload = function () {
            resolve(reader);
        };
        reader.onerror = reject;
        reader.readAsDataURL(file);
    })
}

function encodeURL(hostURL, params) {
    let _url = '';
    if (params) {
        const _keys = Object.keys(params);
        const _values = Object.values(params);
        _keys.forEach((_key) => {
            _url = _url + _key + '=' + params[_key] + '&';
        });
        _url = _url.substr(0, _url.length - 1);
        _url = hostURL + '?' + _url;
        return _url;
    } else {
        return hostURL;
    }
}